package userModel

import (
	"commons/record"
	"commons/util/md5Util"
	"github.com/astaxie/beego/orm"
	"models"
	"time"
)

func UserPassword(userPass string) string {
	var prefix = "###"
	var salt = "qwe$#fgdergwqe"
	str := salt + userPass
	return md5Util.Encryption(str) + prefix
}
func Register(userNickname string, userPass string, sex int, avatar string, ip string) (id int64, err error) {
	model := orm.NewOrm()
	user := new(models.CmfUser)
	user.UserType = 2
	user.Sex = sex
	user.LastLoginTime = int(time.Now().Unix())
	user.CreateTime = int(time.Now().Unix())
	user.Avatar = avatar
	user.UserNickname = userNickname
	user.UserLogin = userNickname
	user.UserPass = UserPassword(userPass)
	user.LastLoginIp = ip
	user.UserStatus = 1
	id, err = model.Insert(user)
	if err != nil {
		record.LogError("注册失败" + err.Error())
	}
	return
}
func UpdateToken(user models.CmfUser) (id int64, err error) {
	model := orm.NewOrm()
	id, err = model.Update(&user, "access_token", "last_login_time")
	if err != nil {
		record.LogError("更新token失败" + err.Error())
	}
	return
}

func GetAccessToken(token string) (user models.CmfUser, err error) {
	model := orm.NewOrm()
	err = model.QueryTable(models.CmfUser{}).Filter("access_token", token).One(&user)
	return user, err
}
func GetByUserID(id int64) (user models.CmfUser, err error) {
	model := orm.NewOrm()
	err = model.QueryTable(models.CmfUser{}).Filter("id", id).One(&user)
	return user, err
}
func GetUserNickName(userNickname string) (user models.CmfUser, err error) {
	model := orm.NewOrm()
	err = model.QueryTable(models.CmfUser{}).Filter("user_nickname", userNickname).One(&user)
	return user, err
}
